﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using com.woodsoft.core;
using EQ1.Elements;
using System.Xml;
using com.woodsoft.core.Files;
using EQ1.Objects;

namespace EQ1.Controls {
  public class Combobox:Control, IUIElement<Combobox> {
    public Combobox ( UIDocument doc , string name ) : base( doc , name ) {
    }
    public Combobox ( UIDocument doc ) : this( doc , "Combobox" ) {
    }

    #region IUIElement<Combobox> Members

    public void Validate ( Combobox val , string name ) {
      UIClass par = ( UIClass ) this.ParentNode;

      if( val.LocalName != name ) {
        Combobox el = new Combobox( ( UIDocument ) val.OwnerDocument , name );
        el.Copy( val );
        val = el;
      }

      if( par.GetElement( name ) != null )
        par.RemoveElement( name );

      par.AppendChild( val );
    }

    public void Copy ( Combobox val ) {
      base.Copy( val );

      if( !string.IsNullOrEmpty( this.Button ) ) {
        this.Button = val.Button;
        if( val.ListHeight != null )
          this.ListHeight = val.ListHeight;
        if( val.Choices != null )
          this.Choices = val.Choices;
      }
    }

    #endregion

    public string Button {
      get {
        return this.GetElement( "Button" ).InnerText;
      }
      set {
        this.Validate( "Button" , value );
      }
    }
    public int? ListHeight {
      get {
        return int.Parse( this.GetElement( "ListHeight" ).InnerText );
      }
      set {
        this.Validate( "ListHeight" , value.ToString() );
      }
    }
    public XmlNodeList Choices {
      get {
        return this.GetElementsByTagName( "Choices" );
      }
      set {
        foreach( XmlNode nd in value ) {
          if( nd.LocalName == "Choices" ) {
            this.AddChoice( nd );
          }
        }
      }
    }
    public void AddChoice (XmlNode val ) {
      if( !string.IsNullOrEmpty( val.InnerText ) && val.LocalName == "Choices" ) {
        for( int i = this.Choices.Count - 1 ; i >= 0 ; i-- ) {
          if( val.InnerText == this.Choices[i].InnerText ) {
            this.ReplaceChild( val , this.Choices[i] );
            return;
          }
        }

        this.AddElement( "Choices" , val.InnerText );
      }
    }
  }
}
